package com.langsin.my0628;
import com.langsin.bean.User;
import com.langsin.shihao.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;


public class shihaoTest {
    @Test
    public void testCache1() throws Exception{
        //mybatis一级缓存是存在sqlsession的内存map里的
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession = sessionFactory.openSession();
        //查询第一个
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryByID(702);
        System.out.println(user);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //同一个sqlsession查询第二次
        User user1 = mapper.queryByID(702);
        System.out.println(user1);
        //同一个会话对象进行了增删改，缓存就会失效
    }
    //二级缓存 需要我们的对象能序列化，二级缓存有可能存入硬盘里的

    @Test
    public void testCache2() throws Exception{
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(stream);
        SqlSession session = sqlSessionFactory.openSession();
        //第一个会话的查询
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.queryByID(702);
        System.out.println(user);
        session.close();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //第二个会话
        SqlSession session1 = sqlSessionFactory.openSession();
        UserMapper mapper1 = session1.getMapper(UserMapper.class);
        User user1 = mapper1.queryByID(702);
        System.out.println(user1);
        session1.close();
    }
}